<!DOCTYPE html>
<html lang="en">

<head>
    <title>Document</title>
    <style>
        .operation div {
            position: absolute;
        }
    </style>
</head>

<body>
    <div>
        <div id="di">
            <div id="my">

            </div>
        </div>
        <div id="operation">
            <div>
                <h1>分数：<span id="score">0</span></h1>
            </div>
            <div>
                <div style="text-align: center;">
                    <button onclick="start()">开始</button>
                    <button onclick="stop()">停止</button>
                </div>
            </div>
            <div>
                <table id="myButton">
                    <tr>
                        <td></td>
                        <td></td>
                        <td></td>
                    </tr>
                    <tr>
                        <td></td>
                        <td></td>
                        <td></td>
                    </tr>
                    <tr>
                        <td></td>
                        <td></td>
                        <td></td>
                    </tr>
                </table>
            </div>
        </div>

    </div>
    <script>
        var di = document.getElementById("di");
        di.style.float = "left"
        di.style.display = "inline"
        di.style.height = Math.floor(window.innerHeight * 1 / 20) * 20  + 'px';
        di.style.width = Math.floor(window.innerWidth * 0.6 / 20) * 20  + 'px';
        di.style.backgroundColor = 'Gray';
        di.style.margin = "0px auto";
        di.style.position = "relative";

        var score = document.getElementById("score")

        var operation = document.getElementById("operation")
        operation.style.float = "right"
        operation.style.display = "inline"
        operation.style.height = Math.floor(window.innerHeight * 1 / 20) * 20 + 'px';
        operation.style.width = Math.floor(window.innerWidth * 0.35 / 20) * 20 + 'px';

        var my = document.getElementById("my");
        my.style.height = "20px";
        my.style.width = "20px";
        my.style.backgroundColor = "Orange";
        my.style.position = "absolute"
        my.style.top = "0px";
        my.style.left = "0px";

        var myButton = document.getElementById("myButton")
        myButton.style.height = "200px"
        myButton.style.width = "200px"
        myButton.style.margin = "120px auto"

        var shangButton = myButton.children[0].children[0].children[1]
        shangButton.style.backgroundColor = "red";
        shangButton.style.border = "2px solid black"

        var zuoButton = myButton.children[0].children[1].children[0]
        zuoButton.style.backgroundColor = "yellow";
        zuoButton.style.border = "2px solid black"

        var xiaButton = myButton.children[0].children[2].children[1]
        xiaButton.style.backgroundColor = "blue";
        xiaButton.style.border = "2px solid black"


        var youButton = myButton.children[0].children[1].children[2]
        youButton.style.backgroundColor = "green";
        youButton.style.border = "2px solid black"

        

        

        var myGame = (function () {
            var my = document.getElementById("my");
            var myHeight = Number(my.style.height.slice(0, -2));
            var myWidth = Number(my.style.height.slice(0, -2));

            var parent = my.parentElement
            var yLimit = Number(parent.style.height.slice(0, -2)) - myHeight;
            var xLimit = Number(parent.style.width.slice(0, -2)) - myWidth;

            var xPos = Number(my.style.top.slice(0, -2))
            var yPos = Number(my.style.left.slice(0, -2))
            var xStep = 0; // → +    
            var yStep = 0;// ↓ +
            var step = myWidth;

            var yiDong = undefined;
            var myBody = (function(){
                var bodyXYArr = [];
                var bodyCount = 0;
                var headXY = [0,0];
                var bodyDivArray = []
                var i = 0;
                function moveBody(){
                    if(bodyDivArray.length < bodyCount ){
                        let bd = getBody()
                        bodyDivArray.splice(i,0,bd)
                        di.appendChild(bd)
                        i++
                    }
                    if(bodyCount!=0){

                        i = i-1<0?bodyCount-1:i-1;
                        bodyDivArray[i].style.left = bodyXYArr[0][0] + 'px'
                        bodyDivArray[i].style.top = bodyXYArr[0][1] + "px"
                    }
                }
                function getBody(){
                    let oneBody = document.createElement("div");
                    oneBody.style.height = "20px";
                    oneBody.style.width = "20px";
                    oneBody.style.backgroundColor = "white";
                    oneBody.style.position = "absolute"
                    return oneBody
                }
                return function(){
                    return{
                        addBody: function(){
                            bodyCount += 1;
                            score.innerText = bodyCount;
                            bodyXYArr.splice(0,0,headXY)
                            console.log("add body:"+ bodyXYArr.toString())
                        },
                        bodyMove: function(headX,headY){
                            
                            bodyXYArr.splice(0,0,headXY)
                            headXY = [headX,headY];
                            if(bodyXYArr.length > bodyCount){
                                bodyXYArr.pop();
                            }
                            moveBody();
                        },
                        bodyCheck: function(x,y){
                            bodyXYArr.forEach(xy=>{
                                if(xy[0] == x && xy[1] == y){
                                    return true;
                                }
                            });
                            return false;
                        },
                        ballCheak: function(ballXY){
                            if(ballXY[0] == headXY[0]&&ballXY[1]==headXY[1]){
                                return true;
                            }
                            bodyXYArr.forEach(xy=>{
                                if(xy[0] == ballXY[0] && xy[1] == ballXY[1]){
                                    return true;
                                }
                            });
                            return false;

                        }
                    }
                }
            })();

            //114514
            var ball = (function (){
                let X =  Number( di.style.width.slice(0,-2))
                let Y = Number( di.style.height.slice(0,-2))

                let XY = [0,0]

                let ball = document.createElement("div");
                ball.style.height = '20px';
                ball.style.width = '20px';
                ball.style.backgroundColor = "red";
                ball.style.position = 'absolute';
                ball.style.top = "-20px"
                ball.style.left = "-20px"

                function setBall(){
                    let ballXY = [0,0]
                    do{
                        ballXY = [Math.floor( Math.random()*X/20) *20, Math.floor( Math.random()*Y/20) *20]
                    }while(myBody().ballCheak(ballXY))
                    ball.style.top = ballXY[1] + "px"
                    ball.style.left = ballXY[0] + "px"
                    XY = ballXY;
                }

                return function(){
                    return{
                        isEatBall:function(headXY){
                            
                            if(headXY[0]==XY[0]&&headXY[1]==XY[1]){
                                setBall();
                                return true;
                            }
                            return false;
                        },
                        start:function(){
                            setBall();
                            di.appendChild(ball)
                        }
                    }
                }
            })();



            function main() {
                yPos += yStep;
                xPos += xStep;

                if (xPos > xLimit || xPos < 0) {
                    xPos -= xStep;
                    return
                    // clearInterval(yiDong)
                    // alert("game over")
                }
                if (yPos > yLimit || yPos < 0) {
                    yPos -= yStep;
                    return;
                    // clearInterval(yiDong)
                    // alert("game over");
                }
                my.style.left = xPos + "px";
                my.style.top = yPos + "px";
                myBody().ballCheak(xPos,yPos)
                if( ball().isEatBall([xPos,yPos] ) ){
                    myBody().addBody()
                }
                myBody().bodyMove(xPos,yPos);

            }

            return function () {
                return {
                    start: function () {
                        yStep = 0;
                        xStep = step;
                        ball().start();
                        if (yiDong == undefined) {
                            yiDong = setInterval(main, 200)
                        }
                    },
                    stop: function () {
                        clearInterval(yiDong)
                        yiDong = undefined;
                    },
                    shang: function () {
                        yStep = -1 * step;
                        xStep = 0;
                    },
                    xia: function () {
                        yStep = step;
                        xStep = 0;
                    },
                    zuo: function () {
                        xStep = -1 * step;
                        yStep = 0;
                    },
                    you: function () {
                        xStep = step;
                        yStep = 0;
                    },
                }
            }
        })();

        function start() {
            myGame().start();
        }
        function stop() {
            myGame().stop();
        }

        function myGoTop() {
            myGame().shang();
        }
        shangButton.addEventListener("mousemove", myGoTop);

        function myGoLeft() {
            myGame().zuo();
        }
        zuoButton.addEventListener("mousemove", myGoLeft);

        function myGoDown() {
            myGame().xia();
        }
        xiaButton.addEventListener("mousemove", myGoDown);

        function myGoRight() {
            myGame().you();
        }
        youButton.addEventListener("mousemove", myGoRight);


    </script>

</body>

</html>